$(document).ready(function(){
	var t = undefined;
	var t2 = undefined;
	var t3 = undefined;
	var taskId = undefined;
	var getUserType = 0;
	var buyType = parseInt($('.buyType').val());
	var device = undefined;
	var lineType = undefined;
	var isTask = 0;

	//查询用户信息
	$.selectUser = function(){
		$.getJSON("/cdt/UserGet?access_token="+$('.access_token').val(),function(json){
			if(parseInt($('.money').val()) < parseInt(json.user.money) && getUserType == 0){
				clearInterval(t2);
				// $('.buyLoading').hide();
				$('.money').val(parseInt(json.user.money))
				// if(buyType == 1 && parseInt($('.presentMoneyTimes').val()) == 0){
				// 	prompt("充值成功，并赠送10元",1);
				// }
				// else{
				// 	prompt("充值成功",1);
				// }
				if(isTask > 0){
					if(isTask == 1){
						$.taskAdd();
						isTask = 0;
					}
					else if(isTask == 2){
						$.taskAddBuyLine();
						isTask = 0;
					}
				}
			}
			else if(getUserType == 1){
				$('.buyLoading').hide();
				$('.money').val(parseInt(json.user.money))
			}
		})
	}

	//查询购买记录
	$.selectBuy = function(){
		$.getJSON("/cdt/taskGet?access_token="+$('.access_token').val()+"&taskId="+taskId,function(json){
			if(json.taskModel.status == 1 && parseInt($('.buyType').val()) == 1){
				clearInterval(t);	
				$('.buyLoading').hide();
				getUserType = 1;
				$.selectUser();
				// $('.scan').removeAttr("disabled");			
				prompt("租借成功",1);
				setTimeout('wx.closeWindow()',3000);
			}
			else if(json.taskModel.status == 1){
				clearInterval(t);
				$('.buyLoading').hide();
				getUserType = 1;
				$.selectUser();
				// $('.scan').removeAttr("disabled");
				prompt("购买成功",1);
				setTimeout('wx.closeWindow()',3000);
			}
			else if(json.taskModel.status == 0 && parseInt($('.buyType').val()) == 1){
				clearInterval(t);	
				$('.buyLoading').hide();
				$('.scan').removeAttr("disabled");
				prompt("租借失败",0);			
			}			
			else if(json.taskModel.status == 0){
				clearInterval(t);	
				$('.buyLoading').hide();
				$('.scan').removeAttr("disabled");
				prompt("购买失败",0);			
			}
			else if(json.taskModel.status == -1){
				clearInterval(t);	
				$('.buyLoading').hide();
				$('.scan').removeAttr("disabled");	
				prompt("没有充电器/充电线了",0);	
			}
			else if(json.taskModel.status == -2 && json.taskModel.status == -3){
				clearInterval(t);	
				$('.buyLoading').hide();
				$('.scan').removeAttr("disabled");	
				prompt("终端发生错误",0);		
			}	
			else if(json.taskModel.status == -5){
				clearInterval(t);	
				$('.buyLoading').hide();	
				$('.scan').removeAttr("disabled");	
				prompt("您借取的充电宝未提取",0);	
			}
			
		})
	}

	// $('.test').bind('click',function(){
	// 		            var xhr = new XMLHttpRequest();
	// 		            xhr.open("GET", "/cdt/chargeCreate?access_token="+$('.access_token').val()+"&channel=wx_pub&amount=100", true);
	// 		            xhr.send();

	// 		            xhr.onreadystatechange = function () {
	// 		                if (xhr.readyState == 4 && xhr.status == 200) {
	// //		                    alert(xhr.responseText);
	// 		                    pingpp.createPayment(xhr.responseText, function(result, err) {
	// 		                        // alert(result);
	// 		                        // alert(err);
	// 		                    });
	// 		                }
	// 		            }		
	// })
	//拉起支付
	$.prepaid = function(amount){
			            var xhr = new XMLHttpRequest();
			            xhr.open("GET", "/cdt/chargeCreate?access_token="+$('.access_token').val()+"&channel=wx_pub&amount="+amount, true);
			            xhr.send();

			            xhr.onreadystatechange = function () {
			                if (xhr.readyState == 4 && xhr.status == 200) {
	//		                    alert(xhr.responseText);
			                    pingpp.createPayment(xhr.responseText, function(result, err) {
			                    	if(result == "success"){
						    			$('.buyLoading').show();
						    			$(".promptBg").show();
						    			t2 = window.setInterval("$.selectUser()",2000); 
						    		}			                        
			                    });
			                }
			            }		
	}

	//购买充电线
	$.taskAddBuyLine = function(){
				$.getJSON("/cdt/taskAddBuyLine?access_token="+$('.access_token').val()+"&terminal="+device+"&lineType="+lineType,function(json){
					if(json.result == 1){
					    taskId = json.taskId
					    $('.buyLoading').show();
					    $(".promptBg").show();
					    $('.scan').attr("disabled","true");
					    getUserType = 0;
					    t = window.setInterval("$.selectBuy()",2000);
					}
					else{
					    prompt(json.msg,0);
					}
				}); 				
	}

	//租借充电宝
	$.taskAdd = function(){
				$.getJSON("/cdt/taskAdd?access_token="+$('.access_token').val()+"&terminal="+device,function(json){
					    	// var tokenJSON = eval('('+json+')');
					   	if(json.result == 1){
					    taskId = json.taskId
					    $('.buyLoading').show();
					    $(".promptBg").show();
					    $('.scan').attr("disabled","true");
					    getUserType = 0;
					    t = window.setInterval("$.selectBuy()",2000); 		
					}
					else{
					    prompt(json.msg,0);
					}
				}); 		
	}

	//点击扫码
	$('.scan').bind('click',function(){
		wx.scanQRCode({
		    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
		    scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
		    success: function (res) {
		    	var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
		    	//存储返回设备号
		    	device = result.split('qrcode=')[1];
		    	//租借充电宝
		    	if (buyType == 1) {
			    	if(parseInt($('.money').val()) >= 100){
			    		$.taskAdd();
			    	}
			    	else{
			    		$('.prompt .message').empty();
			    		$('.prompt .message').append(
								'<p>'+
								'<span class="font1">余额不足</span>'+
								'<br/>'+
								'<span class="font2">借充电宝需要100元押金</span>'+
								'<br/>'+
								'<span class="font3">首次体验，送10元，可用于购买数据线</span>'+
								'</p>'
			    			)
			    		$('.prompt').show();
			    		$('.promptBg').show();
			    	}
			    }
			    //购买iPhone5/6数据线
			    else if(buyType == 2){
			    	lineType = 1;			    	
			    	if(parseInt($('.money').val()) >= 10){
			    		$.taskAddBuyLine();	
			    	}
			    	else{
			    		$('.prompt .message').empty();
			    		$('.prompt .message').append(
								'<p>'+
								'<span class="font1">余额不足</span>'+
								'<br/>'+
								'<span class="font2">购买数据线需要10元</span>'+
								'</p>'
			    			)
			    		$('.prompt').show();
			    		$('.promptBg').show();
			    	}
			    }
			    //购买安卓数据线
			    else if(buyType == 3){
			    	lineType = 3;
			    	if(parseInt($('.money').val()) >= 10){
			    		$.taskAddBuyLine();							
			    	}
			    	else{
			    		$('.prompt .message').empty();
			    		$('.prompt .message').append(
								'<p>'+
								'<span class="font1">余额不足</span>'+
								'<br/>'+
								'<span class="font2">购买数据线需要10元</span>'+
								'</p>'
			    			)
			    		$('.prompt').show();
			    		$('.promptBg').show();
			    	}		    	
			    }
			    //购买iPhone4数据线
		    	else if(buyType == 4){
			    	lineType = 2;		    		
			    	if(parseInt($('.money').val()) >= 10){
			    		$.taskAddBuyLine();
			    	}
			    	else{
			    		$('.prompt .message').empty();
			    		$('.prompt .message').append(
								'<p>'+
								'<span class="font1">余额不足</span>'+
								'<br/>'+
								'<span class="font2">购买数据线需要10元</span>'+
								'</p>'
			    			)
			    		$('.prompt').show();
			    		$('.promptBg').show();
			    	}		    	
			    }			    
			}
		});	
	});

	$('.yes').bind('click',function(){
		if(buyType == 1){
			isTask = 1;		
			$.prepaid(10000);
		}
		else if(buyType == 2 || buyType == 3 || buyType == 4){
			isTask = 2;		
			$.prepaid(1000);
		}
		$('.prompt').hide();
		$('.promptBg').hide();
	});

	$('.no').bind('click',function(){
		$('.prompt').hide();
		$('.promptBg').hide();
	})
})